package com.dome.base.service.impl;

import com.dome.base.constant.CodeConstants;
import com.dome.base.service.SubmitTokenService;
import com.dome.base.utils.AssertUtil;
import com.dome.base.utils.JedisTokenUtil;
import com.dome.client.config.exception.PublicException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class SubmitTokenServiceImpl implements SubmitTokenService {

    private static final String TOKEN_NAME = "submit_token";


    @Override
    public String createToken() {
        return JedisTokenUtil.createToken();
    }

    @Override
    public boolean checkToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(token)) {// header中不存在token
            token = request.getParameter(TOKEN_NAME);
            AssertUtil.notEmpty(token,"提交token不能为空");
        }

        if (!JedisTokenUtil.existsToken(token)) {
            throw new PublicException(CodeConstants.NO_REPEAT_SUBMIT,"请勿重复提交,请刷新后再试");
        }
        //必须存在删除成功.限制一次只能提交一次
        long del = JedisTokenUtil.delToken(token);
        if (del==0) {
            throw new PublicException(CodeConstants.NO_REPEAT_SUBMIT,"请勿重复提交,请刷新后再试");
        }
        return true;
    }

    @Override
    public long delToken(String key) {
        return JedisTokenUtil.delToken(key);
    }

}